#!/usr/bin/perl
# 2013/10/26 convert map file to aso file

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;


if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [map file] -o [output score with p-value]\n";
}

my %opt;
getopts("i:o:", \%opt);
my $FILE_map = $opt{i};
my $FILE_out = $opt{o};


#---------------------------------------
# read data
#---------------------------------------
my %association;
my %location;
my $fh_map = IO::File->new($FILE_map) or die "cannot open $FILE_map: $!";
while($_ = $fh_map->getline()){
	s/\r?\n//;
	my ($id, $chr1, $loc1, $direction1, $mapQ1, $peakName1, $peakLoc1, $chr2, $loc2, $direction2, $mapQ2, $peakName2, $peakLoc2, $type, $num, $locations) = split /\t/;

	if($peakName1 eq $peakName2){
		next;
	}

	$location{$peakName1} = $chr1 . ":" . $peakLoc1;
	$location{$peakName2} = $chr2 . ":" . $peakLoc2;

	my $key = "$peakName1\t$peakName2";
	if($chr1 eq $chr2){
		if($loc2 < $loc1){
			$key = "$peakName2\t$peakName1";
		}
	}else{
		if($chr1 eq 'III' or ($chr1 eq 'II' and $chr2 eq 'I')){
			$key = "$peakName2\t$peakName1";
		}
	}
	$association{$key}++;
}
$fh_map->close();

#---------------------------------------
# output association file
#---------------------------------------
my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
foreach my $key(keys %association){
	my ($bin1, $bin2) = split /\t/, $key;
	$fh_out->print(join("\t", $bin1, $location{$bin1}, $bin2, $location{$bin2}, $association{$key}) . "\n");
}
$fh_out->close();

